// 登录 权限等有关的

import { defineStore } from 'pinia'
import { reactive, toRefs } from 'vue'
import { useRouter } from 'vue-router'
import { Auth } from '@/request/api/common/index'
import { dynamicRouters } from '@/router/routers.js'
import { globalVariable } from '@/stores/modules/useGlobalStore'

import { encryption } from '@/utils/index'
// 全部路由汇总
const allRoutes = dynamicRouters

console.log('本地配置全的所有路由的汇总：allRoutes', allRoutes)
export const authVariable = defineStore('authVariable', () => {
  const router = useRouter()
  const state = reactive({
    userInfo: {},
    userAuthInfo: {}, // 用户权限信息
    routerTree: [], // 用户菜单路由
    isAuthManageShow: false,

  })

  const methods = {
    // 根据用户名 密码登录
    login(userInfo) {
      const user = encryption({
        data: userInfo,
        key: 'pigxpigxpigxpigx', // :pigxpigxpigxpigx  =>pig-ui的加密key
        param: ['password'],
      })

      // eslint-disable-next-line no-async-promise-executor
      return new Promise(async (resolve, reject) => {
        try {
          const response = await Auth.loginByUsername(user.username, user.password, user.code, user.randomStr)
          state.userInfo = response?.data || {}
          // 给pig权限使用的
          localStorage.setItem('token', response?.data?.accessToken)
          localStorage.setItem('refresh_token', response?.data?.refreshToken?.tokenValue)

          // 获取用户权限信息
          await methods.getUserAuth()
          // 加上用户菜单的逻辑
          const menuRes = await methods.getMenuRouter()
          resolve(menuRes || [])
        }
        catch (err) {
          if (err.status === 401) {
            window.$message.warning(err.response?.data?.msg ?? '账户名或密码错误，请重新输入！')
            reject(err)
          }
        }
      })
    },
    // 退出登录
    logout() {
      const { setDictAll } = globalVariable()
      return new Promise((resolve, reject) => {
        Auth.userLogout()
          .then((response) => {
            state.userInfo = {}
            state.userAuthInfo = {}
            state.routerTree = []
            setDictAll({})

            localStorage.clear()

            resolve(response || {})
            router.push('/login')
          })
          .catch((error) => {
            reject(error)
            router.push('/login')
          })
      })
    },
    // 获取用户路由菜单
    getMenuRouter() {
      // eslint-disable-next-line no-async-promise-executor
      return new Promise(async (resolve, reject) => {
        const res = await Auth.getUserMenu(
          //   {
          //     parentId:-1 ,
          //     systemFlag:1
          // }
        )

        if (!res?.data?.length) {
          window.$message.info('该用户未分配菜单权限，请联系管理员！')
          return false
        }

        methods.generateUserRoutes(res.data).then((list) => {
          if (list?.length) {
            list.forEach((v) => {
              router.addRoute(v)
            })
          }

          console.log('106', router.getRoutes())
          resolve(list || [])
        })
      })
    },
    hasPermission: (routers, menu) => {
      return routers?.filter((item) => {
        if (item?.children?.length) {
          item.children = methods.hasPermission(item.children, menu)
        }
        return methods.treePermission(item, menu)
      })
    },
    treePermission: (router, menu) => {
      return menu.some((v) => {
        // eslint-disable-next-line eqeqeq
        if (v.path && v.path == router.path) {
          return router
        }
        else if (v.children && v.children.length > 0) {
          return methods.treePermission(router, v.children)
        }
        else {
          return false
        }
      })
    },
    // 生成用户路由
    generateUserRoutes(menuRoutes) {
      // eslint-disable-next-line no-async-promise-executor
      return new Promise(async (resolve) => {
        const authMenu = methods.hasPermission(allRoutes, menuRoutes) || []

        methods.setRouterTree(authMenu || [])
        resolve(authMenu)
      })
    },
    setRouterTree: (data) => {
      state.routerTree = data
    },
    // 获取用户权限信息
    async getUserAuth() {
      const res = await Auth.getUserAuthInfo()
      state.userAuthInfo = res?.data || {}
    },
    setAuthManageShow(isShow) {
      state.isAuthManageShow = isShow
    },
  }
  return { ...toRefs(state), ...methods }
}, {
  persist: {
    enabled: true,
    strategies: [
      {
        storage: localStorage,
        paths: ['userInfo', 'userAuthInfo', 'routerTree'],
      },
    ],
  },
})
